console.log('加载page_zy_product.js')
/* ===== selfplayingmethodlist =====：自营列表*/
myApp.onPageInit('selfplayingmethodlist', function (page) {
	console.log('page selfplayingmethodlist load');
    var selfplaymenthodpageitem = 10;
    
    //下拉加载的参数初始化
    // Loading flag
	var loading = false;
    // Append items per load
	var selfplaymenthoditemsPerLoad = 10;
	
	/***城市选择***/
    $$.getJSON(url_get_city, {}, function (ajaxresult) {
        if(ajaxresult.code==1){
            var data_selfplayingmethodcity = ajaxresult.data;
            var html_selfplayingmethodcity = myApp.playingMethodCityTemplate(data_selfplayingmethodcity);
            $$('div.selfplayingmethodcity ul').html(html_selfplayingmethodcity);
        }else{
            ajaxfail(ajaxresult.msg);
        }
        
        //点击city
        $$('.selfplayingmethodcity a.btn_item').click(function(){
            $$(this).toggleClass('active');
        });

    });
    
    $$('.filter_submit').click(function(){
    	var city='';
        //更新标题
        if($$('.selfplayingmethodcity a.active').length>1){
			$$('.selfplayingmethodcity a.active').each(function(){
				city+=$$(this).data('city')+',';
			});
		}else if($$('.selfplayingmethodcity a.active').length==1){
			city=$$('.selfplayingmethodcity a.active').data('city');
		}
        if(!city){city='城市'}
        $$('.selfplayingmethodcity_title span').html(city);
        //刷新页面
        getselfplaymethodlist(0,selfplaymenthodpageitem,'refresh');        
    });
   
    /***项目类型选择***/
    $$.getJSON(url_get_selfplayingmethodtype, {}, function (ajaxresult) {
        //console.log(ajaxresult);
        if(ajaxresult.code==1){                   
            var data_selfplayingmethodtype = ajaxresult.data;
            var html_selfplayingmethodtype = myApp.playingmethodtypeTemplate(data_selfplayingmethodtype);
            $$('div.selfplayingmethodtype ul').html(html_selfplayingmethodtype);

            $$('.selfplayingmethodtype a.btn_item').click(function(){
            	//清除之前的选项
                $$('.selfplayingmethodtype a.btn_item').removeClass('active');
                //选定当前选项
				$$(this).addClass('active');
                //更新标题
                var type = '';
                if($$(this).data('id')=='0'){
                	type='类型';
                } else {type=$$(this).html();} 
                $$('.selfplayingmethodtype_title span').html(type);
                //刷新页面
                getselfplaymethodlist(0,selfplaymenthodpageitem,'refresh');
            });
        }else{
            ajaxfail(ajaxresult.msg);
        }
    });
    
    /***排序选择***/
    $$('.selfplayingmethodsort a.btn_item').click(function(){
    	//清除之前的选项
    	$$('.selfplayingmethodsort a.btn_item').removeClass('active');
    	//选定当前选项
		$$(this).addClass('active');
    	//更新标题
    	var sort = '';
        if($$(this).data('id')=='0'){
        	sort='排序';
        }else{sort=$$(this).html();}     
        $$('.selfplayingmethodsort_title span').html(sort);
    	//刷新页面
    	getselfplaymethodlist(0,selfplaymenthodpageitem,'refresh');
    });
    
    //滚动加载
    // 注册'infinite'事件处理函数
    $$('#selfplayingmethodlist .infinite-scroll').on('infinite', function () {
     // 如果正在加载，则退出
     if (loading) return;
     // 设置flag
     loading = true;
     // 模拟1s的加载过程
     setTimeout(function () {
        // 重置加载flag
        loading = false;
        // last load index
		var lastIndex = $$("input[name='selfplayingmethod_lastIndex']").val();
		// Generate new items HTML and Update last loaded index
		getselfplaymethodlist(lastIndex,selfplaymenthoditemsPerLoad,'append'); 
      }, 1000);
    });

    //首次加载项目列表
	$$.getJSON(url_get_selfplayingmethodlist, {cityId:'',limit:selfplaymenthodpageitem,offset:0}, function (ajaxresult) {
		//console.log(ajaxresult);
		if(ajaxresult.code==1){
			if(ajaxresult.data.length < selfplaymenthodpageitem){
        		//如果项目不够，解绑滚动刷新事件
                myApp.detachInfiniteScroll($$('#selfplayingmethodlist .infinite-scroll'));
                $$('#selfplayingmethodlist .infinite-scroll-preloader').hide();
            }
			//数据写入模板
			var data_selfplayingmethodlist = ajaxresult.data;
			var html_selfplayingmethodlist = myApp.playSelfItemTemplate(data_selfplayingmethodlist);
    		$$('#selfplayingmethodlist .div_selfplayingmethodcontent').html(html_selfplayingmethodlist);
    		
    		//页面第一次加载
    		// Last loaded index
    		var lastIndex=$$('.div_selfplayingmethodcontent .selfplayitem').length;
    		//console.log($$('.div_selfplayingmethodcontent .selfplayitem'));
    		//console.log("初次加载："+lastIndex);
    		$$("input[name='selfplayingmethod_lastIndex']").val(lastIndex);
		}else{
			ajaxfail(ajaxresult.msg);
		}
        
	});
	
    //subnav的收放
	$$(".selfplayingmethodcity_title").click(function(){
		var stop=false;
		//关闭其他
    	if ($$('.selfplayingmethodtype').hasClass('grade-w-roll')){
            $$('.selfplayingmethodtype').removeClass('grade-w-roll');
            stop=true;
        };
        if ($$('.selfplayingmethodsort').hasClass('grade-w-roll')){
            $$('.selfplayingmethodsort').removeClass('grade-w-roll');
            stop=true;
        };
        //打开关闭自身
        if ($$('.selfplayingmethodcity').hasClass('grade-w-roll')) {
            $$('.selfplayingmethodcity').removeClass('grade-w-roll');
            $$("#selfplayingmethodlist").removeClass('with-shadow');
        }else {
        	if(stop){
        		setTimeout("$$('.selfplayingmethodcity').addClass('grade-w-roll')",500);
        	}else{
        		$$("#selfplayingmethodlist").addClass('with-shadow');
                $$('.selfplayingmethodcity').addClass('grade-w-roll');
            }
        }        
    });
    
    $$(".selfplayingmethodtype_title").click(function(){
    	var stop=false;
    	if ($$('.selfplayingmethodcity').hasClass('grade-w-roll')){
            $$('.selfplayingmethodcity').removeClass('grade-w-roll');
            stop=true;
        };
        if ($$('.selfplayingmethodsort').hasClass('grade-w-roll')){
            $$('.selfplayingmethodsort').removeClass('grade-w-roll');
            stop=true;
        };
        if ($$('.selfplayingmethodtype').hasClass('grade-w-roll')) {
            $$('.selfplayingmethodtype').removeClass('grade-w-roll');
            $$("#selfplayingmethodlist").removeClass('with-shadow');
        }else {
        	if(stop){
        		setTimeout("$$('.selfplayingmethodtype').addClass('grade-w-roll')",500);
        	}else{
        		$$("#selfplayingmethodlist").addClass('with-shadow');
                $$('.selfplayingmethodtype').addClass('grade-w-roll');
            }
        }        
    });
    
    $$(".selfplayingmethodsort_title").click(function(){
    	var stop=false;
    	if ($$('.selfplayingmethodtype').hasClass('grade-w-roll')){
            $$('.selfplayingmethodtype').removeClass('grade-w-roll');
            stop=true;
        };
        if ($$('.selfplayingmethodcity').hasClass('grade-w-roll')){
            $$('.selfplayingmethodcity').removeClass('grade-w-roll');
            stop=true;
        };

        if ($$('.selfplayingmethodsort').hasClass('grade-w-roll')) {
            $$('.selfplayingmethodsort').removeClass('grade-w-roll');
            $$("#selfplayingmethodlist").removeClass('with-shadow');
        }else {
        	if(stop){
        		setTimeout("$$('.selfplayingmethodsort').addClass('grade-w-roll')",500);
        	}else{
        		$$("#selfplayingmethodlist").addClass('with-shadow');
                $$('.selfplayingmethodsort').addClass('grade-w-roll');
            }
        }        
    });    
});

/* ===== selfplayingmethoddetail =====：详情页 */
myApp.onPageInit('selfplayingmethoddetail', function (page) {
	console.log('page selfplayingmethoddetail load');
	var selfplayid=$$("#selfplayingmethoddetail").data("id");
	/*******背景图*******/
	var selfplaydetailswiper = new Swiper('.swiper-selfplaydetail', {
		pagination:".swiper-pagination-selfplaydetail",
		loop:true,
	    autoplay:5000,
	    autoplayDisableOnInteraction:false
	});
	/*******加载日历*******/
	var i,j;
	//获取发团日期
	var freetimeDays = $$('input[name="freetimeDays"]').val();
	freetimeDays = freetimeDays.split(',');
	var dayrange = [];
	for(i in freetimeDays){
		//去除空元素
		freetimeDays[i] = freetimeDays[i].replace(/(^\s+)|(\s+$)/g,"");
		if(freetimeDays[i].length !=0){
			freetimeDays[i]=freetimeDays[i].split('-');
			//月份从0开始
			var newele = new Date(parseInt(freetimeDays[i][0]),parseInt(freetimeDays[i][1])-1,parseInt(freetimeDays[i][2]));
			dayrange.push(newele);
		}else{
			freetimeDays.splice(i,1);
		}
	}
	//console.log(dayrange);
	//获取每个发团日期下的价格
	/*var priceDetail = $$('input[name="priceDetail"]').val();
	var pofdate = {};
	priceDetail = priceDetail.split(',');
	for(i in priceDetail){
		//去除空元素
		priceDetail[i] = priceDetail[i].replace(/(^\s+)|(\s+$)/g,"");
		if(priceDetail[i].length !=0){
			priceDetail[i]=priceDetail[i].split(':');
			pofdate[priceDetail[i][0]]=priceDetail[i][1];
		}else{
			priceDetail.splice(i,1);
		}
	}*/
	//console.log(pofdate);
	//获取每个发团日期下的成团人数
	var personDetail = $$('input[name="personDetail"]').val();
	var perofdate = {};
	personDetail = personDetail.split(',');
	for(i in personDetail){
		//去除空元素
		personDetail[i] = personDetail[i].replace(/(^\s+)|(\s+$)/g,"");
		if(personDetail[i].length !=0){
			personDetail[i]=personDetail[i].split(':');
			perofdate[personDetail[i][0]]=personDetail[i][1];
		}else{
			personDetail.splice(i,1);
		}
	}
	//console.log(perofdate);
	var monthNames = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月' , '9月' , '10月', '11月', '12月'];
	var calendarInline = myApp.calendar({
	    container: '#calendar-inline-container',
	    value: [new Date()],
	    dayNamesShort:['周日','周一','周二','周三','周四','周五','周六'],
	    monthNames:monthNames,
	    rangesClasses: [
		                    {
		                        cssClass: 'trip-day',
		                        range: dayrange
		                    }
	                    ],
    	toolbarTemplate:'<div class="toolbar calendar-custom-toolbar" style="background:#fff;">' +
				            '<div class="toolbar-inner">' +
				                '<div class="left">' +
				                    '<a href="#" class="link icon-only"><i class="icon icon-back color-green"></i></a>' +
				                '</div>' +
				                '<div class="center"></div>' +
				                '<div class="right">' +
				                    '<a href="#" class="link icon-only"><i class="icon icon-forward color-green"></i></a>' +
				                '</div>' +
				            '</div>' +
				        '</div>',
		onOpen: function (p) {
			$$('.calendar-custom-toolbar .center').text(p.currentYear + '年' + monthNames[p.currentMonth]);
			//设定发团日期
	        $$('#calendar-inline-container .trip-day').each(function(){
	        	$$(this).find('span.perinfo').remove();
	        	var d = $$(this).data('date');
	        	var p = perofdate[d];
	        	var html_tripDay = myApp.playSelfTripDayTemplate(p);
	        	$$(this).append(html_tripDay);
	        });
	         //toolbar event
            $$('.calendar-custom-toolbar .left .link').on('click', function () {
                calendarInline.prevMonth();
            });
            $$('.calendar-custom-toolbar .right .link').on('click', function () {
                calendarInline.nextMonth();
            });
	    },
	    onMonthYearChangeStart: function (p) {
	    	$$('.calendar-custom-toolbar .center').text(p.currentYear + '年' + monthNames[p.currentMonth]);
	    	//设定发团日期
	        $$('#calendar-inline-container .trip-day').each(function(){
	        	$$(this).find('span.perinfo').remove();
	        	var d = $$(this).data('date');
	        	var p = perofdate[d];
	        	var html_tripDay = myApp.playSelfTripDayTemplate(p);
	        	$$(this).append(html_tripDay);
	        });
	    },
	    
	});
	var calHeight = $$("#calendar-inline-container").offset().top-60;
	$$('#selfplayingmethoddetail .toolbar .checkDays').click(function(){
		$$("#selfplayingmethoddetail .page-content").scrollTop(calHeight);
	});
	/*******预定popup*******/
	$$('#selfplayingmethoddetail .toolbar .order').click(function(){
		myApp.popup(".popup-zydetailorder");
	});
	//选项收放
	$$(".popup-zydetailorder .list-group-title").click(function(){
		if($$(this).hasClass('active')){
			$$(this).parent().find('.list-item').hide();
			$$(this).removeClass('active');
			$$(this).find('i').html('chevron_right');
		}else{
			$$(this).parent().find('.list-item').show();
			$$(this).addClass('active');
			$$(this).find('i').html('chevron_down');
		}
	});
	//出行人员
	$$('.popup-zydetailorder .personChoose .add').click(function(){
		var perNum = parseInt($$(this).parent().find('.num').html());
		perNum += 1;
		$$(this).parent().find('.num').html(perNum);
	});
	$$('.popup-zydetailorder .personChoose .minus').click(function(){
		var perNum = parseInt($$(this).parent().find('.num').html());
		if(perNum > 0){
			perNum -= 1;
			$$(this).parent().find('.num').html(perNum);
		}
	});
	
	/*******加载行程介绍和价格介绍*******/
	$$.getJSON(url_get_selfplaydetaildesc, {id:selfplayid}, function (ajaxresult) {
		if(ajaxresult.code==1){
			var data_selfplayingmethoddesc = ajaxresult.data;
			
			//图片写入模板
			var html_selfplaydescline = myApp.selfPlayDescLineTemplate(data_selfplayingmethoddesc);
			var html_selfplaydescprice = myApp.selfPlayDescPriceTemplate(data_selfplayingmethoddesc);
    		$$('#desc ul').html(html_selfplaydescline);
    		$$('#price ul').html(html_selfplaydescprice);
    		
    		//加载完毕显示
    		$$('#selfplayingmethoddetail div.loader').addClass("hidden");
    		$$('#selfplayingmethoddetail div.selfdesc').removeClass("hidden");
    		
    		//行程介绍和价格介绍的图片高度和宽度
			var descLineHeight = parseFloat(data_selfplayingmethoddesc.descLineAppHeight);
			var descLineWidth  = parseFloat(data_selfplayingmethoddesc.descLineAppWidth);
			var descPriceHeight = parseFloat(data_selfplayingmethoddesc.descPriceAppHeight);
			var descPriceWidth  = parseFloat(data_selfplayingmethoddesc.descPriceAppWidth);
			//console.log('descline-origin:w='+descLineWidth+';h='+descLineHeight);
			//console.log('descprice-origin:w='+descPriceWidth+';h='+descPriceHeight);
			
			//设备宽度
			var devW = parseFloat($$('#selfplayingmethoddetail div.selfdesc').width());
			//显示的实际尺寸
			var descLineHeight = parseInt(devW/descLineWidth*descLineHeight);
			var descPriceHeight = parseInt(devW/descPriceWidth*descPriceHeight);
			//console.log('descline-actuel:w='+devW+';h='+descLineHeight);
			//console.log('descprice-actuel:w='+devW+';h='+descPriceHeight);
    		
    		//导航点击事件
    		//内容导航
    	    $$("#selfplayingmethoddetail .buttons-row .button").click(function(){
    	    	$$("#selfplayingmethoddetail .buttons-row .button").removeClass('active');
    	    	$$(this).addClass("active");
    	    	var targetId="#"+$$(this).data('id');
    	    	var targetY=$$(targetId).offset().top+$$("#selfplayingmethoddetail .page-content").scrollTop()-44;
    	    	$$("#selfplayingmethoddetail .page-content").scrollTop(targetY);
    	    });
    	    //顶部内容导航
    	    $$("#selfplaymethoddetail-subnav .buttons-row .button").click(function(){
    	    	$$("#selfplaymethoddetail-subnav .buttons-row .button").removeClass('active');
    	    	$$(this).addClass("active");
    	    	var targetId="#"+$$(this).data('id');
    	    	var targetY=$$(targetId).offset().top+$$("#selfplayingmethoddetail .page-content").scrollTop()-44;
    	    	$$("#selfplayingmethoddetail .page-content").scrollTop(targetY);
    	    });
    	    
    	    //内容导航栏的位置
    	    var buttonrowY=$$("#selfplayingmethoddetail .buttons-row").offset().top;
    	    
    	    //行程介绍起点，subnavbar高44px+2px
    	    var descY=$$("#desc").offset().top-46;
    	    //行程介绍高度
    	    var descimgH=descLineHeight;
    	    
    	    //价格介绍起点
    	    //#price .card-footer高45px, #desc和#price间隔10px 
    	    var priceY=descY+45+descimgH+10;
            //价格介绍高度
    	    var priceimgH=descPriceHeight;
    	    
            //页面滚动，导航定位
    	    $$("#selfplayingmethoddetail .page-content").scroll(function(){
    	    	var top=$$(this).scrollTop();
    	    	if(top>22){
    	    		$$('.backtozylist').hide();
    	    	}else{
    	    		$$('.backtozylist').show();
    	    	}
    	    	//固定在顶部
    	    	if(top>buttonrowY){
    	    		if(!$$("#selfplayingmethoddetail .buttons-row").hasClass('hidden')){
    	    			$$("#selfplayingmethoddetail .buttons-row").addClass('hidden');
    	    		}    		
    	    		if($$("#selfplaymethoddetail-subnav").hasClass('hidden')){
    	    			$$("#selfplaymethoddetail-subnav").removeClass('hidden');
    	    		}
    	    	}else{
    	    		if($$("#selfplayingmethoddetail .buttons-row").hasClass('hidden')){
    	    			$$("#selfplayingmethoddetail .buttons-row").removeClass('hidden');
    	    		}    		
    	    		if(!$$("#selfplaymethoddetail-subnav").hasClass('hidden')){
    	    			$$("#selfplaymethoddetail-subnav").addClass('hidden');
    	    		}
    	    	}
    	    	//button active
    	    	if(top<priceY){
    	    		$$("#selfplayingmethoddetail .buttons-row .button").removeClass('active');
    	        	$$("#selfplayingmethoddetail .buttons-row a[data-id='desc']").addClass("active");   		
    	        	$$("#selfplaymethoddetail-subnav .buttons-row .button").removeClass('active');
    	        	$$("#selfplaymethoddetail-subnav .buttons-row a[data-id='desc']").addClass("active");
    	    	}    	    	
    	    	else if(top>priceY){
    	    		$$("#selfplayingmethoddetail .buttons-row .button").removeClass('active');
    	        	$$("#selfplayingmethoddetail .buttons-row a[data-id='price']").addClass("active");   		
    	        	$$("#selfplaymethoddetail-subnav .buttons-row .button").removeClass('active');
    	        	$$("#selfplaymethoddetail-subnav .buttons-row a[data-id='price']").addClass("active");
    	    	}
    	    });
		}else{
			ajaxfail(ajaxresult.msg);
		}
        
	});
});
